# @Data  : 2020/01/02 20:31
# @Author: xushibo
# @File  : CardInfoByExcel.py

import os
from ..assistant.ExcelOpts import ExcelOpts

ROOT_PATH = os.path.dirname(os.path.abspath(__file__)).split(os.sep + "Lib")[0]
_TEMPLATE_PATH = os.path.join(ROOT_PATH, "Case", "Templates", "Template.xls")

TITLE = ['ICCID', 'IMSI', 'KI', 'ESN', 'PIN1', 'PUK1', 'PIN2', 'PUK2', 'IMSI2', 'KI2', 'ATTR1', 'ATTR2', 'ATTR3',
         'ATTR4', 'ATTR5', 'ATTR6', 'ATTR7', 'ATTR8', 'ATTR9', 'ATTR10']
_TITLE_DICT = {
    'ICCID': "0", 'IMSI': "1", 'KI': "2", 'ESN': "3", 'PIN1': "4", 'PUK1': "5", 'PIN2': "6",
    'PUK2': "7", 'IMSI2': "8", 'KI2': "9", 'ATTR1': "10", 'ATTR2': "11", 'ATTR3': "12", 'ATTR4': "13",
    'ATTR5': "14", 'ATTR6': "15", 'ATTR7': "16",
    'ATTR8': "17", 'ATTR9': "18", 'ATTR10': "19"
}

_NECESSARY_KEY_ICCID = 'ICCID'
_NECESSARY_KEY_IMSI = "IMSI"

_LINE_DICT = {}

_START_ROW = 1


class CardInfoByExcel(ExcelOpts):
    def __init__(self, file_path=_TEMPLATE_PATH, sheet_name="Batch Business"):
        super().__init__(file_path=file_path, sheet_name=sheet_name)
        self.clear(start_row=_START_ROW)

    def write_to_excel(self, list_dict: list):
        i = 0
        for dict in list_dict:
            assert self.check_keys(dict)
            _line_dict = self.comb_dict(dict)
            for col in _line_dict.keys():
                self.write(_START_ROW + i, int(col), _line_dict[col])
            i += 1
        self.save()

    def comb_dict(self, dict):
        _line_dict = {}
        sorted_list = sorted(dict.keys(), key=TITLE.index)
        for key_col in sorted_list:
            for key_row, value_row in dict.items():
                if key_col == key_row:
                    _line_dict[_TITLE_DICT[key_col]] = dict[key_row]
        return _line_dict

    def check_keys(self, kwargs: dict):
        assert (_NECESSARY_KEY_ICCID in kwargs.keys() and _NECESSARY_KEY_IMSI in kwargs.keys()), "Necessary keys required!"
        for key in kwargs.keys():
            if key not in _TITLE_DICT.keys():
                return False
        return True


if __name__ == "__main__":
    pass
